package www.dianbaozu.com.ui.server.channelSetting

import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.netease.nim.uikit.api.NIMHelper
import com.netease.nim.uikit.api.SessionHelper
import com.netease.nim.uikit.xpopup.CreateXPopupHelper
import com.netease.nim.uikit.xpopup.PopupViewEntity
import com.netease.nimlib.sdk.team.constant.TeamFieldEnum
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.FlowPreview
import www.dianbaozu.com.R
import www.dianbaozu.com.databinding.FragmentChannelSettingBinding
import www.dianbaozu.com.extension.requestUniversally
import www.wen.com.common.lib.base.fragment.BaseLoadingFragment
import www.wen.com.common.lib.base.module.BaseViewModel
import www.wen.com.common.lib.data.entities.ChannelInfo
import www.wen.com.common.lib.data.entities.GroupingEntity
import www.wen.com.common.lib.data.entities.RequestBodyParameter
import www.wen.com.common.lib.extension.*
import www.wen.com.common.lib.helper.loading.KeyHelper
import www.wen.com.common.lib.helper.loading.TitleBarUniversalAdapter

@AndroidEntryPoint
class ChannelSettingFragment : BaseLoadingFragment<FragmentChannelSettingBinding>(),
    View.OnClickListener {
    private val channelId by lazy { SessionHelper.currentChannelVO?.channelId ?: 0 }
    private val sessionId by lazy { requireActivity().intent.getStringExtra("sessionId") ?: "" }

    private val serverId by lazy { requireActivity().intent.getStringExtra("serverId") ?: "" }

    private var mGroupId: Int = -1

    override fun actionRight() {
        patchChannel(channelId)
    }

    private val channelSettingViewModel: ChannelSettingViewModel by viewModels()

    override val viewModel: BaseViewModel
        get() = channelSettingViewModel

    override fun getLayoutId(): Int = R.layout.fragment_channel_setting

    override fun isEnableLoadingHelper(): Boolean = true

    override fun getTitleBarUniversalAdapter(): TitleBarUniversalAdapter =
        TitleBarUniversalAdapter(
            requireActivity(),
            "频道设置",
            action = ::titleAction,
            isShowRightText = true,
            rightText = "保存",
            rightTextColor = getColorAgency(R.color.colorFFFFFF)
        )

    override fun lazyInitView() {
        dataBinding.apply {
            listener = this@ChannelSettingFragment
            observeListen()
            channelSettingViewModel.requestUniversally(
                viewModelScope = lifecycleScope,
                request = { appDataManage ->
                    appDataManage.requestChannelId(channelId)
                },
                isShowToastTip = false
            ) { channelEntity ->
                initChannel(channelEntity)
            }
        }
    }

    private fun observeListen() {
        observeObject(KeyHelper.CHANNEL_CREATE_FRAGMENT_UI_KEY, this, GroupingEntity::class.java) {
            dataBinding.tvGroupName.text = groupName
            mGroupId = groupId
        }
    }

    private fun initChannel(channelEntity: ChannelInfo) {
        dataBinding.apply {
            mGroupId = channelEntity.groupId
            etPleaseEnterAGroupName.setText(channelEntity.channelName)
            tvGroupName.text = channelEntity.groupName
            etIntroduction.setText(channelEntity.channelDesc)
        }
    }

    @FlowPreview
    private fun deleteChannel(channelId: Long) {
        channelSettingViewModel.deleteChannel(channelId) {
            toast("删除频道成功")
            finishMyself()
            postObject(KeyHelper.FINISH_CONTACT,true)
            postObject(KeyHelper.REFRESHING_SERVER_LIST_KEY1, Object())
        }
    }

    @FlowPreview
    private fun patchChannel(channelId: Long) {
        dataBinding.apply {
            val channelName = etPleaseEnterAGroupName.text.toString().trim()
            val channelDesc = etIntroduction.text.toString().trim()
            val bodyParameter = RequestBodyParameter(
                channelDesc = channelDesc,
                channelName = channelName,
                groupId = mGroupId
            )
            channelSettingViewModel.patchChannel(channelId, bodyParameter) {
                NIMHelper.updateTeamFields(sessionId, mapOf(Pair(TeamFieldEnum.Name, channelName)))
                toast("修改频道成功")
                navBack()
            }
        }
    }

    override fun onClick(v: View) {
        when (v) {
            dataBinding.tvDeleteChannel -> {
                PopupViewEntity().let {
                    it.context = requireActivity()
                    it.standardAlertPopupViewTitle = "删除频道"
                    it.standardAlertPopupViewContent =
                        "确定要删除 ${SessionHelper.currentChannelVO?.channelName} 吗?\n该操作无法撤销"
                    it.standardAlertPopupViewCancelContent = "取消"
                    it.standardAlertPopupViewConfirmContent = "删除"
                    it.finishOnCancel = true
                    it.cancelFunction = { popupView ->
                        popupView.dismiss()
                    }
                    it.confirmFunction = { popupView ->
                        deleteChannel(channelId)
                        popupView.dismiss()
                    }
                    it.isShow = true
                    CreateXPopupHelper.createShowStandardAlertPopupView(it)
                }
            }
            dataBinding.tvGroupName -> {
                channelSettingViewModel.requestUniversally(
                    viewModelScope = lifecycleScope,
                    isShowToastTip = false,
                    request = { appDataManage ->
                        appDataManage.requestServerGroup(serverId)
                    }
                ) { groups ->
                    nav(
                        R.id.action_channelSettingFragment_to_groupingSortingFragment2,
                        Bundle().apply {
                            groups.first { group ->
                                mGroupId == group.groupId
                            }.also {
                                it.isSelected = true
                                putParcelableArrayList(
                                    KeyHelper.BUNDLE_DATA,
                                    groups as ArrayList<GroupingEntity>
                                )
                            }
                        })
                }
            }
        }
    }

}